#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <vector>
#include <stdio.h>

using std::cout;
using std::endl;

// 定义一个函数指针和对应的函数指针数组
typedef void (*handler_t)();
std::vector<handler_t> handlers;

//定义一个临时任务1
void fun_one()
{
  cout << "这是临时任务1" << endl; 
  sleep(0.4);
}

// 定义一个临时任务2
void fun_two()
{
  cout << "这是临时任务2-------------------" << endl;
  sleep(0.7);
}

// 将两个任务加载到函数指针数组中
void Load()
{
  handlers.push_back(fun_one);
  handlers.push_back(fun_two);
}

// 执行两个任务
void handler()
{
  if (handlers.empty())
    Load();
  for (handler_t iter : handlers)
  {
    iter();
  }
}

int main()
{
  pid_t pid = fork();

  if (pid < 0)
  {
    printf("%s fork error\n", __FUNCTION__);
    return 1;
  }
  else if (pid == 0) // 子进程
  {
    printf("child is run, pid is : %d\n", getpid());
    sleep(5);
    exit(0);
  }
  else
  {
    int status = 0;
    pid_t ret = 0;
    do 
    {
      ret = waitpid(-1, &status, WNOHANG);
      if (ret == 0)
      {
        cout << "child is running" << endl;
      }
      handler(); 
    } while (ret == 0);

    if (WIFEXITED(status) && ret == pid)
    {
      cout << "wait child 5s success, child return code is : " <<  WEXITSTATUS(status) << endl;
    }
    else{
      cout << "wait child failed, return." << endl;
      return 1;
    }
  } 


  return 0;
}
